groovy custom send notification slack in vars folder

You can use the Slack Notification Plugin in Jenkins to send notifications to a Slack channel after a build is completed. You can also use Groovy Postbuild Plugin to send notifications when a build fails¹³.

Here's an example of how you can send a notification to Slack using Groovy:

groovy
def notifySlack(String buildStatus = 'STARTED') {
    // Build status of null means success
    def color = buildStatus == 'STARTED' ? 'good' : 'danger'
    def message = buildStatus == 'STARTED' ? "Build started: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}](${env.BUILD_URL})" : "Build failed: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}](${env.BUILD_URL})"
    slackSend (color: color, message: message)
}

You can modify this code to change the color of the message. For example, you can set it to red for success and blue for failure:

groovy
def notifySlack(String buildStatus = 'STARTED') {
    // Build status of null means success
    def color = buildStatus == 'STARTED' ? '#FF0000' : '#0000FF'
    def message = buildStatus == 'STARTED' ? "Build started: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}](${env.BUILD_URL})" : "Build failed: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}](${env.BUILD_URL})"
    slackSend (color: color, message: message)
}

Reference:

groovy - How to send Slack notification after a Jenkins pipeline build .... https://stackoverflow.com/questions/39140191/how-to-send-slack-notifica tion-after-a-jenkins-pipeline-build-failedAccessed 4/8/2023.

(2) Jenkins - Unable to send slack notifications using Groovy postbuild .... https://stackoverflow.com/questions/53572838/jenkins-unable-to-send-slack-notifications-using-groovy-postbuild-pluginAccessed 4/8/2023.

(3) Slack Notification Plugin. https: //www.jenkins.io/doc/pipeline/steps/slack/Accessed 4/8/2023.

(4) groovy - Notify slack user from Jenkins pipeline when build fails .... h ttps://stackoverflow.com/questions/62127056/notify-slack-user-from-jenkins-pipeline-when-build-failsAccessed 4/8/2023.